package devcken.springframework.ui;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.util.CookieGenerator;

@Controller("navigationIndicatingInterceptor")
public class NavigationIndicatingInterceptor implements HandlerInterceptor
{
	private static final String _NAVIGATION_PATH_COOKIE_NAME = "_NAVIGATION_PATH";
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception
	{
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception
	{
		String requestUrl = request.getRequestURL().toString();
		
		if (!requestUrl.contains("resources"))
		{
			int position = requestUrl.indexOf(request.getContextPath());
			
			String navigationPath = requestUrl.substring(position);
			
			CookieGenerator cookie = new CookieGenerator();
			
			cookie.setCookieName(_NAVIGATION_PATH_COOKIE_NAME);
			cookie.setCookieMaxAge(Integer.MAX_VALUE);
			
			cookie.addCookie(response, navigationPath);
		}
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception
	{

	}
}